<template>
  <div class="system-session-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="system-session-search mb15">
        <el-input size="default" placeholder="请输入用户ID" style="max-width: 180px" v-model="state.tableData.param.userId" clearable>
        </el-input>
        <el-input size="default" placeholder="请输入IP地址" style="max-width: 180px" v-model="state.tableData.param.ipAddress" clearable>
        </el-input>
        <el-select v-model="state.tableData.param.status" placeholder="请选择状态" clearable style="max-width: 180px">
          <el-option label="活跃" :value="1"></el-option>
          <el-option label="已结束" :value="0"></el-option>
        </el-select>
        <el-button size="default" type="primary" class="ml10" @click="getTableData">
          <el-icon>
            <ele-Search />
          </el-icon>
          查询
        </el-button>
        <el-button size="default" type="danger" class="ml10" @click="onBatchEndSessions" :disabled="state.multipleSelection.length === 0">
          <el-icon>
            <ele-SwitchButton />
          </el-icon>
          批量下线
        </el-button>
      </div>
      <el-table 
        :data="state.tableData.data" 
        v-loading="state.tableData.loading" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="sessionId" label="会话ID" show-overflow-tooltip width="200">
          <template #default="scope">
            <el-tooltip :content="scope.row.sessionId" placement="top">
              <span>{{ scope.row.sessionId.substring(0, 20) }}...</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="clientSessions" label="客户端会话" show-overflow-tooltip>
          <template #default="scope">
            <div v-for="(session, clientId) in scope.row.clientSessions" :key="clientId" class="client-session">
              <el-tag size="small" class="mb5">
                {{ clientId }}
              </el-tag>
              <div class="session-scopes">
                <el-tag v-for="scopeItem in session.scopes" :key="scopeItem" size="small" type="info" class="mr5">
                  {{ scopeItem }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="loginTime" label="登录时间" show-overflow-tooltip></el-table-column>
        <el-table-column prop="lastActivity" label="最后活动" show-overflow-tooltip></el-table-column>
        <el-table-column prop="expiresAt" label="过期时间" show-overflow-tooltip></el-table-column>
        <el-table-column prop="ipAddress" label="IP地址" show-overflow-tooltip></el-table-column>
        <el-table-column prop="status" label="状态" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
              {{ scope.row.status === 1 ? '活跃' : '已结束' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button 
              size="small" 
              text 
              type="primary" 
              @click="onViewSessionDetail(scope.row)"
            >
              <el-icon>
                <ele-View />
              </el-icon>
              详情
            </el-button>
            <el-button 
              size="small" 
              text 
              type="danger" 
              @click="onEndSession(scope.row)"
              :disabled="scope.row.status === 0"
            >
              <el-icon>
                <ele-SwitchButton />
              </el-icon>
              下线
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="onHandleSizeChange"
        @current-change="onHandleCurrentChange"
        class="mt15"
        :pager-count="5"
        :page-sizes="[10, 20, 30]"
        v-model:current-page="state.tableData.param.page"
        background
        v-model:page-size="state.tableData.param.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.tableData.total"
      >
      </el-pagination>
    </el-card>
    
    <!-- 会话详情对话框 -->
    <el-dialog title="会话详情" v-model="state.sessionDetailDialog.visible" width="800px">
      <div v-if="state.sessionDetailDialog.data" class="session-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="会话ID">
            <el-tag>{{ state.sessionDetailDialog.data.sessionId }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户名">
            {{ state.sessionDetailDialog.data.username }}
          </el-descriptions-item>
          <el-descriptions-item label="登录时间">
            {{ state.sessionDetailDialog.data.loginTime }}
          </el-descriptions-item>
          <el-descriptions-item label="最后活动">
            {{ state.sessionDetailDialog.data.lastActivity }}
          </el-descriptions-item>
          <el-descriptions-item label="过期时间">
            {{ state.sessionDetailDialog.data.expiresAt }}
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ state.sessionDetailDialog.data.ipAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="状态" :span="2">
            <el-tag :type="state.sessionDetailDialog.data.status === 1 ? 'success' : 'danger'">
              {{ state.sessionDetailDialog.data.status === 1 ? '活跃' : '已结束' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户代理" :span="2">
            <div class="user-agent">{{ state.sessionDetailDialog.data.userAgent }}</div>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="client-sessions-detail mt20">
          <h4>客户端会话详情</h4>
          <el-table :data="getClientSessionsArray(state.sessionDetailDialog.data.clientSessions)" style="width: 100%">
            <el-table-column prop="clientId" label="客户端ID"></el-table-column>
            <el-table-column prop="loginTime" label="登录时间"></el-table-column>
            <el-table-column prop="scopes" label="作用域">
              <template #default="scope">
                <el-tag v-for="scopeItem in scope.row.scopes" :key="scopeItem" size="small" class="mr5">
                  {{ scopeItem }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.sessionDetailDialog.visible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 批量下线对话框 -->
    <el-dialog title="批量下线会话" v-model="state.batchEndDialog.visible" width="500px">
      <el-form :model="state.batchEndDialog.form" label-width="80px">
        <el-form-item label="下线原因">
          <el-input 
            v-model="state.batchEndDialog.form.reason" 
            type="textarea" 
            placeholder="请输入下线原因"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <div class="batch-info">
            <p>将下线 <strong>{{ state.multipleSelection.length }}</strong> 个会话</p>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.batchEndDialog.visible = false">取 消</el-button>
          <el-button type="danger" @click="confirmBatchEnd">确认下线</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="oidcSessions">
import { reactive, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getSessionList, endSession, batchEndSessions } from '/@/api/oidc/sessions';

// 定义变量内容
const state = reactive({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      page: 1,
      size: 10,
      userId: '',
    ipAddress: '',
      status: '',
    },
  },
  multipleSelection: [],
  sessionDetailDialog: {
    visible: false,
    data: null,
  },
  batchEndDialog: {
    visible: false,
    form: {
      reason: '',
    },
  },
});

// 将客户端会话对象转换为数组
const getClientSessionsArray = (clientSessions: any) => {
  if (!clientSessions) return [];
  return Object.keys(clientSessions).map(clientId => ({
    clientId: clientId,
    ...clientSessions[clientId],
  }));
};

// 初始化表格数据
const getTableData = () => {
  state.tableData.loading = true;
  getSessionList(state.tableData.param)
    .then((res: any) => {
      state.tableData.data = res.data.items;
      state.tableData.total = res.data.total;
    })
    .finally(() => {
      state.tableData.loading = false;
    });
};

// 处理多选
const handleSelectionChange = (selection: any[]) => {
  state.multipleSelection = selection;
};

// 查看会话详情
const onViewSessionDetail = (row: any) => {
  state.sessionDetailDialog.data = row;
  state.sessionDetailDialog.visible = true;
};

// 结束单个会话
const onEndSession = (row: any) => {
  ElMessageBox.confirm(`确定要结束用户 "${row.username}" 的会话吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      endSession(row.id).then(() => {
        ElMessage.success('会话结束成功');
        getTableData();
      });
    })
    .catch(() => {});
};

// 打开批量下线对话框
const onBatchEndSessions = () => {
  if (state.multipleSelection.length === 0) {
    ElMessage.warning('请选择要下线的会话');
    return;
  }
  state.batchEndDialog.visible = true;
  state.batchEndDialog.form.reason = '';
};

// 确认批量下线
const confirmBatchEnd = () => {
  const sessionIds = state.multipleSelection.map((item: any) => item.id);
  const params = {
    sessionIds: sessionIds,
    reason: state.batchEndDialog.form.reason || '管理员强制下线',
  };
  
  batchEndSessions(params)
    .then(() => {
      ElMessage.success(`批量下线成功，共下线 ${sessionIds.length} 个会话`);
      state.batchEndDialog.visible = false;
      getTableData();
    })
    .catch(() => {
      state.batchEndDialog.visible = false;
    });
};

// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.size = val;
  getTableData();
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.page = val;
  getTableData();
};

// 页面加载时
onMounted(() => {
  getTableData();
});
</script>

<style scoped lang="scss">
.system-session-container {
  .system-session-search {
    display: flex;
    margin-bottom: 10px;
    .el-input,
    .el-select {
      margin-right: 10px;
    }
  }
  
  .client-session {
    margin-bottom: 10px;
    
    .session-scopes {
      margin-top: 5px;
    }
  }
  
  .session-detail {
    .user-agent {
      word-break: break-all;
      font-size: 12px;
      color: #666;
    }
    
    .client-sessions-detail {
      h4 {
        margin-bottom: 10px;
        color: #303133;
      }
    }
  }
  
  .batch-info {
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    
    p {
      margin: 0;
      color: #606266;
    }
  }
}
</style>